import 'dart:io';

import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/model/moto_search.dart';
import 'package:dmz/business/home/widgets/map_widgets.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/tools/map/map_manger.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:dmz/utils/keyboard_util.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

class MotoLocationController extends BaseController {
  late MotoModel data;
  Map<String, Marker> markerMap = {}; //标记点
  LatLng? initLatLng; //初始化车辆位置
  late AMapController mapController;
  String initAddresss = ''; //逆地理位置
  String city = ''; //逆地理位置 城市
  List<SearchResult> searchResults = [];
  SearchResult? selectData;
  TextEditingController textController = TextEditingController();
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    var controllered = Get.find<HomePageController>();
    data = controllered.motoList[controllered.pageIndex];
    getMotoLocation();
    super.onInit();
  }

  ///获取车辆位置
  getMotoLocation({bool isReload = false}) {
    RequestClient().post<Map<String, dynamic>>(APIS.getMotoMsg,
        data: {'ebike_id': data.id, 'cmd': 'Location'}).then((value) async {
      var latLng =
          await EMIMapManger().convertLatLng(value?['lng'], value?['lat']);
      initLatLng = latLng;
      getLocationStr();
      if (isReload) moveCarme(latLng);
      addMarkerMap(latLng, 'moto');
    });
  }

  ///移动镜头
  moveCarme(LatLng latLng) {
    mapController.moveCamera(CameraUpdate.newLatLng(latLng));
  }

  ///添加大头针
  addMarkerMap(LatLng latLng, String key) {
    markerMap.clear();
    var iconed = BitmapDescriptor.fromIconPath(key == 'search'
        ? 'assets/gif/location.gif'
        : 'assets/images/home/main/location_image.png');
    Marker marker = Marker(position: latLng, icon: iconed);
    markerMap[key] = marker;
    update();
  }

  ///地理逆编码
  getLocationStr() async {
    var data = await EMIMapManger().reverseGeocoding(initLatLng!);
    initAddresss = data['formatted_address'];
    city = data['addressComponent']['city'];
    update();
  }

  seleMapApp() {
    EMILoding.showBottomWindow(MapWidgets.seleMapAppWidget((type) {
      type == 0 ? launchAmapApp(initLatLng!) : launchBaiduMapApp(initAddresss);
    }), isDismissible: true);
  }

  // 打开百度地图App
  void launchBaiduMapApp(String address) async {
    // String url =
    //     'baidumap://map/direction?destination=${latLng.latitude},${latLng.longitude}';
    String url = 'baidumap://map/direction?destination=$address';
    try {
      await launchUrl(Uri.parse(url));
    } catch (e) {
      EMILoding.hitLoding('请安装百度地图App'.tr);
    }
  }

  // 打开高德地图App并定位到指定位置
  void launchAmapApp(LatLng latLng) async {
    String url =
        '${Platform.isIOS ? 'iosamap' : 'androidamap'}://openFeature?featureName=OnRideNavi&rideType=elebike&sourceApplication=appname';

    // 构建完整的Scheme URL
    String fullUrl =
        '$url&lat=${latLng.latitude}&lon=${latLng.longitude}&dev=0';
    launchUrl(Uri.parse(fullUrl)).then((value) {
      if (!value) {
        EMILoding.hitLoding('请安装高德地图App'.tr);
      }
    });
  }

  ///位置搜索
  searchAddress(String text) {
    EMIMapManger().searchAddtrssWithString(text, city).then((value) {
      searchResults = value;
      update(['searchList']);
    });
  }

  cleanAll() {
    textController.text = '';
    searchResults.clear();
    update(['searchList']);
  }

  resultClick(SearchResult data) {
    KeyboardUtils.hideKeyboardGex();
    textController.text = data.name ?? '';
    searchResults.clear();
    update(['searchList']);
    var latLng = LatLng(data.latitude!, data.longitude!);
    addMarkerMap(latLng, 'search');
    moveCarme(latLng);
  }

  turnSelect() {
    KeyboardUtils.hideKeyboardGex();
    resultClick(selectData ?? searchResults.first);
  }

  seleMapNavigationApp(SearchResult data) {
    EMILoding.showBottomWindow(MapWidgets.seleMapAppWidget((type) {
      type == 0
          ? launchAmapApp(LatLng(data.latitude ?? 0, data.longitude ?? 0))
          : launchBaiduMapApp(data.name ?? '');
    }), isDismissible: true);
  }
}
